package cn.school.demo.util

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import java.io.*
import java.net.URLEncoder

object ImageUtil {
    //图片解析
    fun imageToBase64(bitmap: Bitmap): String {
        val byteArrayOutputStream =
            ByteArrayOutputStream()
        //图片压缩
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
        val buffer = byteArrayOutputStream.toByteArray()
        return Base64.encodeToString(buffer, Base64.DEFAULT)
    }

    //编码还原图片
    fun base64ToImage(bitmap64: String?): Bitmap {
        val bytes =
            Base64.decode(bitmap64, Base64.DEFAULT)
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    }

    /**
     * 将一张本地图片转化成Base64字符串
     * @param imgPath 本地图片地址
     * @return 图片转化base64后再UrlEncode结果
     */
    fun getImageStrFromPath(imgPath: String?): String? {
        val `in`: InputStream
        var data: ByteArray? = null
        var result: String? = null
        // 读取图片字节数组
        try {
            `in` = FileInputStream(imgPath)
            data = ByteArray(`in`.available())
            `in`.read(data)
            `in`.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        // 对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过再URLEncode的字节数组字符串
//        return URLEncoder.encode(encoder.encode(data));
        try {
            result = URLEncoder.encode(Base64.encodeToString(data, Base64.DEFAULT), "utf-8")
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
        return result
    }
}